use actix_web::{self, scope, get, post, Responder, web, Error};
use serde::{Serialize, Deserialize};
use crate::lbean::user::UserTabBean;
use crate::ldb::{get_db, user_db};
use crate::lservice::user_service as UserSer;
use crate::{result_for_error, result_for_success};

#[derive(Serialize, Deserialize)]
struct UserBean {
    phone: String,
    password: String,
}

#[derive(Serialize, Deserialize)]
struct UserAddBean {
    name: String,
    phone: String,
    password: String,
}

#[post("/add")]
async fn user_add(param: web::Json<UserAddBean>) -> actix_web::Result<impl Responder, Error> {
    // Ok(format!("你来了呀：name:{}, age:{}", param.name, param.age))
    if param.name.is_empty() {
        return Err(actix_web::error::ErrorPaymentRequired("名字不能为空"));
    }

    if param.phone.is_empty() {
        return Err(actix_web::error::ErrorPaymentRequired("手机号不能为空"));
    }

    if param.password.is_empty() {
        return Err(actix_web::error::ErrorPaymentRequired("密码不能为空"));
    }

    let user_bean = UserTabBean::new(&param.name, &param.phone, &param.password);

    if let Err(e) = UserSer::user_add(user_bean).await {
        return Ok(result_for_success!(e.to_string()));
    }

    Ok(result_for_success!("添加成功".to_string()))
}
#[get("/findAll")]
async fn user_find_all() -> impl Responder{
    return match UserSer::user_find_all().await {
        Ok(list) => {
            result_for_success!(list)
        }
        Err(e) => {
            result_for_error!(100, e.to_string())
        }
    }
}
#[get("/findByPhone/{phone}")]
async fn user_find_by_phone(param: web::Path<String>) -> impl Responder{
    let (phone) = param.into_inner();
    return match UserSer::user_find_by_phone(&phone).await {
        Ok(list) => {
            result_for_success!(list)
        }
        Err(e) => {
            result_for_error!(100, e.to_string())
        }
    }
}
#[post("/login")]
async fn login_user(param: web::Json<UserBean>) -> actix_web::Result<impl Responder, Error> {
    // Ok(format!("你来了呀：name:{}, age:{}", param.name, param.age))


    Ok(format!("你来了呀："))
}


